﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aierp.Entities;
using Aierp.Utility.Core;
using Aierp.Utility;
using Aierp.Utility.Data;
using Chloe;
using NLog.Fluent;

namespace Aierp.Repository.Implements
{
    public class CustomersRepository : DbInstance
    {
        public const string OriginalPass = "123a";

        public int Login(string userName, string passWord, SysVisitorCustomer sysVisitor)
        {
            IQuery<C1_Customer> models = Db.Query<C1_Customer>();
            var model = models.Where(a => a.UserName == userName).FirstOrDefault();

            if (model == null) return 0;

            //账户禁用
            if (model.IsDisabled)
            {
                return -2;
            }

            if(model.StatusCode =="DELETE") return -11;//删除
            if (model.StatusCode != "POST") return -12;//未激活

            //验证密码是否正确
            var md5Pass = Md5.md5(passWord + model.PassSalt, 32);
            if (model.Password.Equals(md5Pass, StringComparison.OrdinalIgnoreCase))
            {
                sysVisitor.UserId = model.KeyId;
                sysVisitor.UserName = model.UserName;

                sysVisitor.CurrentCustomer = model;

                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 查询一个客户-根据客户名
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public C1_Customer Find(string key)
        {
            IQuery<C1_Customer> users = Db.Query<C1_Customer>();
            var result = users.Where(c => c.UserName == key).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 查询一个客户-根据邮箱
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public C1_Customer FindByEmail(string email)
        {
            IQuery<C1_Customer> users = Db.Query<C1_Customer>();
            var result = users.Where(c => c.Email == email).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 查询一个客户-根据token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public C1_Customer FindByToken(string token)
        {
            IQuery<C1_Customer> users = Db.Query<C1_Customer>();
            var result = users.Where(c => c.Token == token).FirstOrDefault();
            return result;
        }
        /// <summary>
        /// 查询一个客户-根据ID，只返回指定信息，密码等关键信息不返回
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object FindById(int key)
        {
            IQuery<C1_Customer> users = Db.Query<C1_Customer>();
            var result = users.Where(c => c.KeyId == key).Select(a => new { a.KeyId, a.UserName, a.CustCode, a.DepartmentId, a.CustName, a.QQ, a.Cellphone,a.Email,a.Remark,a.IsDisabled }).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 获取一个列表，供给Grid使用
        /// </summary>
        /// <param name="sortOrder"></param>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="searchTxt"></param>
        /// <returns></returns>
        public string GetList(string sortOrder, int limit, int offset, string searchTxt)
        {
            IQuery<C1_Customer> users = Db.Query<C1_Customer>(); ;
            users = users.Where(u => u.StatusCode != "DELETE");

            var total = users.Count();
            if (limit > 1000) limit = 100;
            
            users = (string.IsNullOrEmpty(sortOrder) || sortOrder == "asc") ? users.OrderBy(a => a.KeyId) : users.OrderByDesc(a => a.KeyId);

            if (!string.IsNullOrEmpty(searchTxt))
            {
                users = users.Where(c => c.UserName.Contains(searchTxt) || c.CustName.Contains(searchTxt));
            }

            var ret =
                users.Select(
                    a =>
                        new
                        {
                            a.KeyId,
                            a.UserName,
                            a.CustCode,
                            a.DepartmentId,
                            a.CustName,
                            a.QQ,
                            a.Cellphone,
                            a.Remark,
                            a.IsDisabled,
                            a.CreateOn
                        });
            var list= ret.Skip(offset).Take(limit).ToList();

            return JSONhelper.GetJsonforBootstrapTable(total, list);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public int Add(C1_Customer item)
        {
            try
            {
                if (item == null) return 0;

                var result = this.Find(item.UserName);//用户名查询重复
                if (result != null) return -2;
                result = this.FindByEmail(item.Email);
                if (result != null) return -9;//邮箱查询重复

                item.CustName = "用户";
                item.CustType = 0;
                item.IsDisabled = false;
                item.StatusCode = "DRAFT";
                item.CreateOn = DateTime.Now;
                item.PassSalt = Md5.randomString();
                item.Password = Md5.md5(Md5.md5(item.Password, 32) + item.PassSalt, 32);
                var ret = Db.Insert(item);

                return ret?.KeyId ?? 0;
            }
            catch (Exception ex)
            {
                var messgae = new StringBuilder();
                messgae.Append("CustomersRepository：Add方法报错，内容如下：\r\n");
                messgae.Append(ex.Message);
                messgae.Append(ex.StackTrace);
                Log.Error(messgae.ToString());
                return 0;
            }           
        }

        /// <summary>
        /// 客户停用
        /// </summary>
        /// <param name="key"></param>
        /// <param name="sysVisitor"></param>
        /// <returns></returns>
        public int Remove(int key, SysVisitor sysVisitor)
        {
            //先检查客户是否存在
            IQuery<C1_Customer> users = Db.Query<C1_Customer>();
            var user = users.Where(c => c.KeyId == key).FirstOrDefault();
            if (user == null) return -2;

            //删除客户表--非物理删除
            user.StatusCode = "DELETE";
            user.DeletedBy = sysVisitor.UserName;
            user.DeletedOn = DateTime.Now;

            return Db.Update(user);//这时只会更新被修改的字段
        }

        /// <summary>
        /// 更新客户
        /// </summary>
        /// <param name="item"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int Update(C1_Customer item, string userName)
        {
            //先检查客户是否存在
            var user = this.Find(item.UserName);
            if (user == null) return -2;
            //更新
            Db.TrackEntity(user);//在上下文中跟踪实体
            user.CustName = item.CustName;
            user.Addr = item.Addr;
            user.Cellphone = item.Cellphone;  
            user.QQ = item.QQ;
            user.IsDisabled = item.IsDisabled;
            user.Remark = item.Remark;
            user.UpdateBy = userName;
            user.UpdateOn = DateTime.Now;
            item.StatusCode = "POST";

            return Db.Update(user);//这时只会更新被修改的字段

        }

        /// <summary>
        /// 更新客户-更新我的信息-只更新3个字段
        /// </summary>
        /// <param name="item"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int UpdateMyInfo(C1_Customer item,string userName)
        {
            //先检查客户是否存在
            var user = this.Find(item.UserName);
            if (user == null) return -2;
            //更新
            Db.TrackEntity(user);//在上下文中跟踪实体
            user.CustName = item.CustName;
            user.Cellphone = item.Cellphone;
            user.QQ = item.QQ;
            user.UpdateBy = userName;
            user.UpdateOn = DateTime.Now;

            return Db.Update(user);//这时只会更新被修改的字段

        }

        /// <summary>
        /// 更新Token
        /// </summary>
        /// <param name="item"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public int UpdateToken(C1_Customer item,string token)
        {
            //先检查客户是否存在
            var user = this.Find(item.UserName);
            if (user == null) return -2;
            //更新
            Db.TrackEntity(user);//在上下文中跟踪实体
            user.Token = token;
            return Db.Update(user);//这时只会更新被修改的字段
        }

        /// <summary>
        /// 更新Token
        /// </summary>
        /// <param name="item"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public int UpdateEmailSendNum(C1_Customer item)
        {
            //先检查客户是否存在
            var user = this.Find(item.UserName);
            if (user == null) return -2;
            //更新
            Db.TrackEntity(user);//在上下文中跟踪实体
            user.EmailSendNum += 1;
            return Db.Update(user);//这时只会更新被修改的字段
        }

        //修改密码
        public int ChangePassWord(int userId, string oldPass, string newPass)
        {
            IQuery<C1_Customer> models = Db.Query<C1_Customer>();
            var u = models.Where(c => c.KeyId == userId).FirstOrDefault();
            if (u == null) return -2;
            oldPass = Md5.md5(oldPass + u.PassSalt, 32);
            if (oldPass != u.Password) return -9;

            Db.TrackEntity(u);//在上下文中跟踪实体
            u.Password = Md5.md5(newPass + u.PassSalt, 32);//更改密码//更改密码
            return Db.Update(u);
        }

        /// <summary>
        /// 设置密码为初始值123a
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int ResetPassWord(int userId)
        {
            IQuery<C1_Customer> models = Db.Query<C1_Customer>();
            var u = models.Where(c => c.KeyId == userId).FirstOrDefault();
            if (u == null) return -2;
            Db.TrackEntity(u);//在上下文中跟踪实体

            u.Password = Md5.md5(Md5.md5(OriginalPass, 32) + u.PassSalt, 32);//更改密码

            return Db.Update(u);
        }

        /// <summary>
        /// 忘记密码，重设
        /// </summary>
        /// <param name="token"></param>
        /// <param name="newPass"></param>
        /// <returns></returns>
        public int ResetPassWord(string token,string newPass)
        {
            IQuery<C1_Customer> models = Db.Query<C1_Customer>();
            var u = models.Where(c => c.Token == token).FirstOrDefault();
            if (u == null) return -2;
            Db.TrackEntity(u);//在上下文中跟踪实体

            u.Password = Md5.md5(Md5.md5(newPass, 32) + u.PassSalt, 32);//更改密码
            u.Token = "";//token清空
            u.EmailSendNum = 0;//重置
            return Db.Update(u);
        }

        /// <summary>
        ///  激活
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int Activation(int userId)
        {
            IQuery<C1_Customer> models = Db.Query<C1_Customer>();
            var u = models.Where(c => c.KeyId == userId).FirstOrDefault();
            if (u == null) return -2;
            Db.TrackEntity(u);//在上下文中跟踪实体

            u.StatusCode = "POST";//
            u.Token = "";//token清空
            u.EmailSendNum = 0;//重置
            return Db.Update(u);
        }

        public int GetHtmlVersion()
        {
            IEnumerable<int> version = Db.SqlQuery<int>("select ConfigValue from Sys_Config where ConfigName='HtmlVersion'");
            var enumerable = version as int[] ?? version.ToArray();
            return enumerable[0];
        }
    }
}
